package cl.uchile.sti.authorization.dao;

import cl.uchile.sti.authorization.model.Permiso;
import cl.uchile.sti.authorization.model.Rol;

import javax.persistence.EntityManager;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Julio Villane
 * Date: 11-12-12
 * Time: 12:34 PM
 */
public class PermisoDAO {

    private static EntityManager entityManager = cambiarPorSpring.getEntityManager();

    private PermisoDAO(){ }

    public static Permiso find(Long id){
        return entityManager.find(Permiso.class, id);
    }

    public static Permiso save(Permiso permiso) {

        if (permiso.getId() == null) {
            entityManager.persist(permiso);
            return permiso;
        } else {
            return entityManager.merge(permiso);
        }
    }

    public static void delete(Permiso permiso){
        List<Rol> roles = RolDAO.getByPermiso(permiso);
        for(Rol rol: roles){
            rol.getPermisos().remove(permiso);
            RolDAO.save(rol);
        }
        entityManager.remove(permiso);
    }
}
